package com.buddy.sds.auth.oauth2.controller;

import com.buddy.sds.auth.entity.SystemUser;
import com.buddy.sds.auth.oauth2.config.OAuth2ConfigProperties;
import com.buddy.sds.auth.oauth2.token.TokenManager;
import com.buddy.sds.auth.oauth2.service.ISystemOauthClientService;
import com.buddy.sds.common.RestApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/auth/oauth")
public class OAuthController {

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private OAuth2ConfigProperties oAuth2ConfigProperties;

    @Autowired
    private ISystemOauthClientService oauthClientService;


    @RequestMapping("authorize")
    public RestApiResponse authorize(String client_id, String client_secret, String grant_type , SystemUser user){

        int status = -1;

        String message = null;

        Object data = null;

        do{


            if(! oauthClientService.checkAppId(client_id)){

                message = "错误的client_id";
                break;
            }

            if(! oauthClientService.checkSecret(client_id,client_secret)){
                message = "错误的client_secret";
                break;
            }



            if(!"password".equals(grant_type)){
                message = String.format("暂不支持%s授权",grant_type);
                break;
            }


            String accessToken = UUID.randomUUID().toString();

            String refreshToken = UUID.randomUUID().toString();





            if(!oAuth2ConfigProperties.isCoverOldToken()){
                //如果不覆盖旧token

                String username = user.getUserName();

                TokenManager.Token token = tokenManager.getToken(username,client_id);

                if(token != null){

                    status = 0;
                    data = token;
                    break;
                }

            }

            long current = System.currentTimeMillis();

            TokenManager.Token token = tokenManager.putToken(user.getUserName(),client_id,accessToken,refreshToken,current + oAuth2ConfigProperties.getTokenExpireSeconds() * 1000,current + oAuth2ConfigProperties.getRefreshTokenExpireSeconds() * 1000);

            data = token;

            status = 0;


        }while (false);


        return new RestApiResponse(status,message,data);
    }
}
